package com.shop.common.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.shop.common.enums.FileTypeEnum;
import org.springframework.util.Assert;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

public class OSSUtil {
    public static Map<String, String> preUpload(String type) {
        String dir = FileTypeEnum.getDirByType(type);
        Assert.notNull(dir, "文件类型错误");

        String endpoint = YmlUtils.get("oss.endpoint");
        String accessKeyId = YmlUtils.get("oss.access-key-id");
        String accessKeySecret = YmlUtils.get("oss.access-key-secret");
        String bucketName = YmlUtils.get("oss.bucket-name");

        String host = "https://" + bucketName + "." + endpoint;
        long expireTime = 300;
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        Date expiration = new Date(expireEndTime);
        PolicyConditions policyConds = new PolicyConditions();
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

        Map<String, String> respMap = new LinkedHashMap<String, String>();
        try {

            OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            respMap.put("accessid", accessKeyId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("domain", YmlUtils.get("oss.domain"));
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return respMap;
    }

    // 补全地址
    public static String completeUrl(String path) {
        // http开头的原样返回
        if (StringUtils.isNull(path) || path.startsWith("http")) {
            return path;
        }
        return YmlUtils.get("oss.domain") + "/" + path;
    }
}
